<?php
/// Copyright (c) 2004-2007, Cain Chen / Hina :: 工程幼稚園
/// All rights reserved. Licensed under the GPL.
/// See the GNU General Public License for more details. (/doc/LICENSE, /doc/COPYRIGHT)

if (!defined('ROOT')) {
	header('HTTP/1.1 403 Forbidden');
	header("Connection: close");
	exit;
}

if(isset($__ts)) unset($__ts);
$__ts = array();

global $blog, $service, $__ts;
# Locale language file support, defualt is en-us.php
if (!isset($blog['blogLanguage'])) {
	$blog['blogLanguage'] = $service['language'];
}
// Locale language file support.
switch($blog['blogLanguage']) {
	case "zh-TW":
	case "zh-CN":
		$languageFile = 'lang/'.$blog['blogLanguage'].'.php';
	break;
	default:
		$languageFile = "";
}
if(!empty($languageFile)) { include ($languageFile); }

function getRespondResultPage($error, $data = null){
	if($error==1) {
		print ("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<response>\n<error>0</error>\n<data>{$data}</data>\n</response>");
	} elseif($error==0) {
		print ("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<response>\n<error>1</error>\n<data>null</data>\n</response>");
	}
	exit;
}

function modifyPluginsSortable() {
	global $blogURL, $database, $activePlugins, $gCacheStorage;
	requireModel('common.setting');
	
	$changeActivePlugins = unserialize(urldecode($_POST['originalActivePlugins']));
	$orderExchange = explode(',', $_POST['orderExchange']);
	$activePlugins = array();
	
	foreach($changeActivePlugins as $asocckey => $plugin) {
		if($orderExchange[1]==0) {
			array_push($activePlugins, $changeActivePlugins[($orderExchange[0]-1)]);
			array_push($activePlugins, $plugin);
			$orderExchange[1] = -1;
		} elseif ($orderExchange[0]==($asocckey+1)) {
			continue;
		} elseif ($orderExchange[1]==($asocckey+1)) {
			array_push($activePlugins, $changeActivePlugins[($orderExchange[0]-1)]);
			array_push($activePlugins, $plugin);
		} else {
			array_push($activePlugins, $plugin);
		}
	}
	/// reset plugin Cache
	$gCacheStorage->setContent('activePlugins',$activePlugins);
	$gCacheStorage->save();
	header('Content-Type: text/xml; charset=utf-8');
	if( setServiceSetting("modifyPluginsSortable", serialize($activePlugins) ) ) {
		getRespondResultPage(1, serialize($activePlugins));
	} else {
		getRespondResultPage(0);
	}
}

function plugin_Sortable() {
	global $service, $blogURL, $database, $activePlugins, $gCacheStorage;
	requireModel('common.setting');
	require_once ('lang/pluginLocal.php');
	
	if (substr(file_get_contents(ROOT.'/cache/CHECKUP'), 0, 3) < 1.5) {
		$_text = _t('Alert ::\r\n - This plugin must be Textcube 1.5 or above. \r\n Please update your textcube and try again.');
		$setupAlert = '<script type="text/javascript">alert("'.$_text.'"); history.go(-1);</script>';
		exit;
	}
	if($gCacheStorage->getContent('activePlugins')) $activePlugins = $gCacheStorage->getContent('activePlugins');
	else {
		$activePlugins = POD::queryColumn("SELECT name FROM {$database['prefix']}Plugins WHERE blogid = ".getBlogId());
		$gCacheStorage->setContent('activePlugins',$activePlugins);
	}
	
	$originalActivePlugins = serialize($activePlugins);
	$xmls = new XMLStruct();
	$sortPlugin = array();
	foreach ($activePlugins as $asocckey => $plugin) {
		$manifest = @file_get_contents(ROOT . "/plugins/$plugin/index.xml");
		if ($manifest && $xmls->open($manifest)) {
			array_push($sortPlugin, array('name'=>htmlspecialchars($xmls->getValue('/plugin/title[lang()]')),
			'version'=>$xmls->getValue('/plugin/version'),
			'description'=>htmlspecialchars($xmls->getValue('/plugin/description[lang()]'))));
		}
	}
	
	list($currentTextcubeVersion) = explode(' ', TEXTCUBE_VERSION, 2);
	$scriptPath = ($currentTextcubeVersion >= 1.8) ? '/resources/script' : '/script';
	$imagesPath = ($currentTextcubeVersion >= 1.8) ? '/resources/image' : '/image';
	
	$tempPath = array('script'=>$scriptPath, 'image'=>$imagesPath);
	
?>
	<style type="text/css" media="screen">
    <!--
	blockquote {
		padding-left: 20px;
	}
	table.dojoDndItem {
		border: 1px solid #efefef;
		height: auto;
		cursor: move;
		margin: 2px 2px;
		padding: 2px 2px;
	}
	tr.sortableHeader td {
		font-weight: bold;
	}
	td.pluginsOrder {
		width: 80px;
		text-align: center;
	}
	td.pluginsName {
		width: 240px;
	}
	td.pluginsVersion {
		width: 80px;
	}
	td.pluginsDescription {
		width: 480px;
	}	
	.ajax-floating-panel {
		background-color: #ffcccc;
	}
    -->
    </style>
	
	<script type="text/javascript" src="<?php echo $service['path'].$tempPath['script'];?>/dojo/dojo.js"></script>
	<script type="text/javascript" language="javascript">
	//<![CDATA[
	String.prototype.replaceAll = function(search, replace){
		var regex = new RegExp(search, "g");
		return this.replace(regex, replace);
	}
	
	try {
		djConfig.parseWidgets = false;
	} catch(e) { alert(e); }
	
	dojo.require("dojo.dnd.HtmlDragAndDrop");

	DragPanel = function(node, type) {
		dojo.dnd.HtmlDragSource.call(this, node, type);
		this.dragClass = "ajax-floating-panel";
		this.opacity = 0.9;
	}
	dojo.inherits(DragPanel, dojo.dnd.HtmlDragSource);
	
	DropPanel = function(node, type) {
		dojo.dnd.HtmlDropTarget.call(this, node, type);
	}
	dojo.inherits(DropPanel, dojo.dnd.HtmlDropTarget);
	
	dojo.lang.extend(DropPanel, {
		onDrop: function(e) {
			this.parentMethod = DropPanel.superclass.onDrop;
			var retVal = this.parentMethod(e);
			delete this.parentMethod;
			if (retVal == true) {
				var originalActivePlugins = document.getElementById("originalActivePlugins");
				var sourcePostion = e.dragObject.domNode.pluginsPos;
				var targetPosition = 0;
				var prevNode = e.dragObject.domNode.previousSibling;
				while (prevNode != null) {
					if ((prevNode.nodeType != 3/* TEXT_NODE */) && (prevNode.className.indexOf("dojoDndItem") != -1)) break;
					prevNode = prevNode.previousSibling;
				}
				if (prevNode != null) {
					targetPosition = prevNode.pluginsPos;
				}
				
				var request = new HTTPRequest("POST", "<?php echo $blogURL;?>/plugin/modifyPluginsSortable");
				PM.addRequest(request, "<?php echo _t('플러그인 설정 데이터를 초기화하고 있습니다.');?>");
				request.onSuccess = function() {
					document.getElementById("originalActivePlugins").innerHTML = this.getText('/response/data');
					PM.removeRequest(this);
					PM.showMessage("<?php echo _t('저장되었습니다.');?>", "center", "bottom");
				}
				request.onError = function() {
					PM.removeRequest(this);
					PM.showErrorMessage("<?php echo _t('저장하지 못했습니다.');?>", "center", "bottom");
				}
				request.send("orderExchange="+sourcePostion+","+targetPosition+"&originalActivePlugins=" + encodeURIComponent(originalActivePlugins.value));
			}
		}
	});
	
	var globalOrder = null;
	
	function initPages() {
		new DropPanel(document.getElementById('pluginContainer'), ["pluginContainer"]);
<?php
	foreach ($sortPlugin as $asocckey => $plugin) {
		echo "\t\tdocument.getElementById('dojoDndItem-{$asocckey}').pluginsPos = ".($asocckey+1).";\n";
		echo "\t\tnew DragPanel(document.getElementById('dojoDndItem-{$asocckey}'), [\"pluginContainer\"]);\n";
	}
?>
	}
	dojo.addOnLoad(initPages);
	//]]>
	</script>

	<div id="sitemap-status" calss="part">
		<h2 class="caption"><span class="main-text"><?php echo pluginLang::plfs('Active Plugins List:');?></span></h2>
		<blockquote><table cellpadding="0" cellspacing="0"><tr><td colspan="4"><blockquote>
		<span><?php echo pluginLang::plfs('This plugin got the plugins which in use in TextCube.');?><?php echo pluginLang::plfs('And you can use drag and drop to sort plugins which will be loaded in your order.');?></span><br />
		<span style="color: #f33;"><?php echo pluginLang::plfs('This plugin must set "pageCache" component setting (control&gt;server) in your config.php file.');?></span><br /><br /></blockquote></td></tr>
		<tr class="sortableHeader"><td class="pluginsOrder"><?php echo pluginLang::plfs('No');?></td><td class="pluginsName"><?php echo pluginLang::plfs('Name');?></td><td class="pluginsVersion"><?php echo pluginLang::plfs('Ver.');?></td><td class="pluginsDescription"><?php echo pluginLang::plfs('Description');?></td></tr></table>
			<div id="pluginContainer" class="pluginContainer">
<?php
	foreach ($sortPlugin as $asocckey => $plugin) {
		echo '<table cellpadding="0" cellspacing="0" class="dojoDndItem" id="dojoDndItem-'.$asocckey.'"><tr>';
		echo '<td class="pluginsOrder">'.($asocckey+1).'</td>';
		echo '<td class="pluginsName">'.$plugin['name'].'</td>';
		echo '<td class="pluginsVersion">'.$plugin['version'].'</td>';
		echo '<td class="pluginsDescription">'.$plugin['description'].'</td>';
		echo '</tr></table>';
	}
?>
		</div>
		</blockquote>
	</div>
	<textarea name="originalActivePlugins" id="originalActivePlugins" style="display:none;"><?php echo $originalActivePlugins;?></textarea>
<?php    
}
?>